/*
Script: Json.js

Copyright 2005-2007 Netvibes Ltd.
All rights reserved.

Credits:
    Partially based on MooTools Framework - copyright (c) 2007 Valerio Proietti, <http://mad4milk.net>
*/

if (typeof UWA == "undefined") var UWA = {};

if (typeof UWA.Json == "undefined") UWA.Json = {};

/*
Class: Json
    Json parser and Stringyfier, See: <http://www.json.org/>
*/

UWA.extend(UWA.Json, {
  
  getType: function(obj){
  	if (obj == undefined) return false;
  	if (obj.htmlElement) return 'element';
  	var type = typeof obj;
  	if (type == 'object' && obj.nodeName){
  		switch(obj.nodeType){
  			case 1: return 'element';
  			case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
  		}
  	}
  	if (type == 'object' || type == 'function'){
  		switch(obj.constructor){
  			case Array: return 'array';
  			case RegExp: return 'regexp';
  			case Class: return 'class';
  		}
  		if (typeof obj.length == 'number'){
  			if (obj.item) return 'collection';
  			if (obj.callee) return 'arguments';
  		}
  	}
  	return type;
  },
  
  encode: function(obj){
		switch( UWA.Json.getType(obj) ){
			case 'string':
				return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
			case 'array':
				return '[' + obj.map(UWA.Json.encode).join(',') + ']';
			case 'object':
				var string = [];
				for (var property in obj) string.push(UWA.Json.encode(property) + ':' + UWA.Json.encode(obj[property]));
				return '{' + string.join(',') + '}';
			case 'number':
				if (isFinite(obj)) break;
			case false:
				return 'null';
		}
		return String(obj);
	},

  decode: function(str){
    var regex = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
    if (typeof str == 'string' && regex.test(str)) {
      return eval('(' + str + ')');
    }
    return null;
  }

});